package com.remenote.remenoteback.context.config;

import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.Expiry;
import com.remenote.remenoteback.entity.vo.UserVo;
import org.checkerframework.checker.index.qual.NonNegative;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

/**
 * @BelongsProject: remenote-back
 * @BelongsPackage: com.remenote.remenoteback.context.config
 * @Author: 23392
 * @CreateTime: 2024-03-18  13:19
 * @Description: TODO
 * @Version: 1.0
 */
@Configuration
public class CacheConfig {
    private static final int tokenExpireTimeInHour = 3;

    private static final long HOUR_DURATION_IN_NANO_SECONDS = 3600L * 1000L * 1000L;

    @Bean
    public Cache<String, UserVo> userCache(){
        return Caffeine.newBuilder()
                .maximumSize(500)
                .expireAfter(new Expiry<String, UserVo>() {
                    @Override
                    public long expireAfterCreate(@NonNull String key, @NonNull UserVo value, long currentTime) {
                        return currentTime + tokenExpireTimeInHour * HOUR_DURATION_IN_NANO_SECONDS;
                    }
                    @Override
                    public long expireAfterUpdate(@NonNull String key, @NonNull UserVo value, long currentTime, @NonNegative long currentDuration) {
                        return currentTime + tokenExpireTimeInHour * HOUR_DURATION_IN_NANO_SECONDS;
                    }
                    @Override
                    public long expireAfterRead(@NonNull String key, @NonNull UserVo value, long currentTime, @NonNegative long currentDuration) {
                        return currentTime + tokenExpireTimeInHour * HOUR_DURATION_IN_NANO_SECONDS;
                    }
                }).build();
    }
}
